'use strict';

const socket = new WebSocket('ws://115.28.101.55:8888');
let id = 0;
// Connection opened
socket.addEventListener('open', function (event) {
    socket.send(JSON.stringify({
        cmd: 'login',
    }));
});

// Listen for messages
socket.addEventListener('message', function (event) {
    let data = JSON.parse(event.data);
    if (data.cmd === 'msg') {
        let chatArea = document.getElementById('chat-area');
        let row = document.createElement('div');
        row.setAttribute("class", "row");
        let message = document.createElement('div');
        if (data.id === id) {
            message.setAttribute("class", "message-right");
        } else {
            message.setAttribute("class", "message-left");
        }
        chatArea.appendChild(row);
        row.append(message);
        message.innerHTML = data.msg;
    } else if (data.cmd === 'login') {
        id = data.id;
    }
});

$('#chat').on('keypress',function(event){
    if(event.keyCode === 13) {
        let content = $('#chat').val();
        socket.send(JSON.stringify({
            cmd: 'msg',
            msg: content,
            id: id,
        }));
        $('#chat').val('');
    }
});